import { useState } from 'react';
import { Upload, Spin } from 'antd';
import 'antd/es/modal/style';
import { PlusOutlined } from '@ant-design/icons';
import type { ConnectProps } from '@/models/connect';
import { UPLOAD_IMAGE_URL } from '@/configs/global';
import ImgCrop from 'antd-img-crop';

export interface UploadImageProps extends ConnectProps {
  forValue: string;
  value?: string;
  onChange?: (file: any) => void;
}
// 上传头像组件
const UploadAvatar = ({ forValue, value, onChange }: UploadImageProps) => {
  const [loading, setLoading] = useState(false);

  const uploadButton = (
    <div>
      <PlusOutlined />
      <div className="ant-upload-text">点击上传</div>
    </div>
  );

  const onUploadChange = (e) => {
    if (!e || !e.file) {
      return e;
    }
    const { file } = e;
    if (file.status === 'uploading') {
      setLoading(true);
    } else {
      setLoading(false);
    }
    if (file.status === 'done' && onChange) {
      onChange(file);
    }
    return true;
  };

  return (
    <Spin spinning={loading} wrapperClassName="spin-container">
      <ImgCrop rotate>
        <Upload
          className="avatar-uploader"
          onChange={onUploadChange}
          name="image"
          listType="picture-card"
          showUploadList={false}
          action={UPLOAD_IMAGE_URL}
          data={{ for: forValue }}
          disabled={loading}
        >
          {value ? (
            <img src={value} alt="avatar" style={{ width: 80, height: 80 }} />
          ) : (
            uploadButton
          )}
        </Upload>
      </ImgCrop>
    </Spin>
  );
};

export default UploadAvatar;
